package com.cjkj.equipment.service.impl;

import com.cjkj.common.core.domain.AjaxResult;
import com.cjkj.common.core.domain.entity.SysDictData;
import com.cjkj.common.exception.ServiceException;
import com.cjkj.common.utils.DateUtils;
import com.cjkj.common.utils.StringUtils;
import com.cjkj.common.utils.uuid.IdUtils;
import com.cjkj.common.constant.EquipmentConstant;
import com.cjkj.equipment.domain.TEquipmentInfo;
import com.cjkj.equipment.domain.dto.EquipmentDataReq;
import com.cjkj.equipment.domain.dto.EquipmentDistributionReq;
import com.cjkj.equipment.domain.vo.EquipmentDataVo;
import com.cjkj.equipment.domain.vo.EquipmentExportVo;
import com.cjkj.equipment.domain.vo.EquipmentImportVo;
import com.cjkj.equipment.mapper.TEquipmentInfoMapper;
import com.cjkj.equipment.service.ITEquipmentInfoService;
import com.cjkj.hospital.domain.THospitalEquipment;
import com.cjkj.hospital.mapper.THospitalEquipmentMapper;
import com.cjkj.system.mapper.SysDictDataMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import static com.cjkj.common.utils.SecurityUtils.getUsername;

/**
 * 设备信息Service业务层处理
 * 
 * @author cjkj
 * @date 2024-08-26
 */
@Slf4j
@Service
public class TEquipmentInfoServiceImpl implements ITEquipmentInfoService 
{
    @Resource
    private TEquipmentInfoMapper tEquipmentInfoMapper;

    @Resource
    private SysDictDataMapper sysDictDataMapper;

    @Resource
    private THospitalEquipmentMapper tHospitalEquipmentMapper;

    /**
     * 查询设备信息
     * 
     * @param id 设备信息主键
     * @return 设备信息
     */
    @Override
    public TEquipmentInfo selectTEquipmentInfoById(String id)
    {
        return tEquipmentInfoMapper.selectTEquipmentInfoById(id);
    }

    /**
     * 查询设备信息列表
     * 
     * @param req 参数信息
     * @return 设备信息
     */
    @Override
    public List<EquipmentDataVo> getTEquipmentInfoList(EquipmentDataReq req) {
        return tEquipmentInfoMapper.selectTEquipmentInfoList(req);
    }

    /**
     * 导出设备列表
     * @param req 参数
     * @return 设备信息
     */
    @Override
    public List<EquipmentExportVo> getTEquipmentExportList(EquipmentDataReq req) {
        return tEquipmentInfoMapper.selectTEquipmentExportList(req);
    }

    /**
     * 新增设备信息
     * 
     * @param tEquipmentInfo 设备信息
     * @return 结果
     */
    @Override
    public int insertTEquipmentInfo(TEquipmentInfo tEquipmentInfo) {

        // 判断设备编号是否已存在
        TEquipmentInfo info = tEquipmentInfoMapper.selectTEquipmentInfoByNo(tEquipmentInfo.getEquipmentNo());
        if(info != null) {
            throw new ServiceException("设备编号已存在！");
        }

        String username = getUsername();
        Date nowDate = DateUtils.getNowDate();

        tEquipmentInfo.setId(IdUtils.fastSimpleUUID());
        tEquipmentInfo.setCreateTime(nowDate);
        tEquipmentInfo.setCreateBy(username);
        tEquipmentInfo.setUpdateTime(nowDate);
        tEquipmentInfo.setUpdateBy(username);
        return tEquipmentInfoMapper.insertTEquipmentInfo(tEquipmentInfo);
    }

    /**
     * 修改设备信息
     * 
     * @param tEquipmentInfo 设备信息
     * @return 结果
     */
    @Override
    public int updateTEquipmentInfo(TEquipmentInfo tEquipmentInfo) {

        // 判断设备是否已分配到了医院，如果分配了，不允许修改
        TEquipmentInfo oldInfo = tEquipmentInfoMapper.selectTEquipmentInfoById(tEquipmentInfo.getId());
        if(oldInfo == null) {
            throw new ServiceException("设备信息不存在！");
        }
        if(EquipmentConstant.DISTRIBUTE_FLAG_YES.equals(oldInfo.getDistributeFlag())) {
            throw new ServiceException("设备已分配医院，不允许修改！");
        }

        // 判断设备编号是否已存在
        TEquipmentInfo info = tEquipmentInfoMapper.selectTEquipmentInfoByNo(tEquipmentInfo.getEquipmentNo());
        if(info != null && !oldInfo.getId().equals(info.getId())) {
            throw new ServiceException("设备编号已存在！");
        }

        tEquipmentInfo.setUpdateTime(DateUtils.getNowDate());
        tEquipmentInfo.setUpdateBy(getUsername());
        return tEquipmentInfoMapper.updateTEquipmentInfo(tEquipmentInfo);
    }

    /**
     * 批量删除设备信息
     * 
     * @param id 需要删除的设备信息主键
     * @return 结果
     */
    @Override
    public int deleteTEquipmentInfoById(String id) {
        TEquipmentInfo oldInfo = tEquipmentInfoMapper.selectTEquipmentInfoById(id);
        if(oldInfo == null) {
            throw new ServiceException("设备信息不存在！");
        }
        if(EquipmentConstant.DISTRIBUTE_FLAG_YES.equals(oldInfo.getDistributeFlag())) {
            throw new ServiceException("设备已分配医院，不允许修改！");
        }

        return tEquipmentInfoMapper.deleteTEquipmentInfoById(id);
    }

    @Override
    public String importEquipment(List<EquipmentImportVo> equipmentInfoList, String operName) {
        if (StringUtils.isNull(equipmentInfoList) || equipmentInfoList.isEmpty()) {
            throw new ServiceException("导入设备数据不能为空！");
        }
        Date nowDate = DateUtils.getNowDate();
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (EquipmentImportVo vo : equipmentInfoList) {
            String equipmentNo = vo.getEquipmentNo();
            String equipmentType = vo.getEquipmentType();

            try {
                // 验证设备类型
                SysDictData dictData = sysDictDataMapper.selectDictDataByTypeAndLabel("equipment_type", equipmentType);
                if(StringUtils.isNull(dictData)) {
                    failureNum ++;
                    failureMsg.append("<br/>").append(failureNum).append("、设备类型：").append(equipmentType).append(" 不存在！");
                    continue;
                }

                // 验证是否已存在这个设备
                TEquipmentInfo equipmentInfo = tEquipmentInfoMapper.selectTEquipmentInfoByNo(equipmentNo);
                if (StringUtils.isNull(equipmentInfo)) {

                    TEquipmentInfo equipment = new TEquipmentInfo();

                    equipment.setId(IdUtils.fastSimpleUUID());
                    equipment.setEquipmentNo(equipmentNo);
                    equipment.setEquipmentType(dictData.getDictValue());
                    equipment.setCreateTime(nowDate);
                    equipment.setCreateBy(operName);
                    equipment.setUpdateTime(nowDate);
                    equipment.setUpdateBy(operName);
                    tEquipmentInfoMapper.insertTEquipmentInfo(equipment);

                    successNum ++;
                    successMsg.append("<br/>").append(successNum).append("、设备号：").append(equipmentNo).append("导入成功！");
                } else {
                    failureNum ++;
                    failureMsg.append("<br/>").append(failureNum).append("、设备号：").append(equipmentNo).append(" 已存在！");
                }
            } catch (Exception e) {
                failureNum ++;
                String msg = "<br/>" + failureNum + "、设备号：" + equipmentNo + " 导入失败：";
                failureMsg.append(msg).append(e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，共 " + failureNum + " 条数据导入失败，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doDistribution(EquipmentDistributionReq req) {

        String tj01Id = req.getTj01Id();
        String tj02Id = req.getTj02Id();
        String tj03Id = req.getTj03Id();
        Date nowDate = DateUtils.getNowDate();
        String username = getUsername();
        // 分配睡眠监测垫
        if(StringUtils.isNotBlank(tj01Id)){
            String[] tj01IdArr = tj01Id.split(",");
            if (!ArrayUtils.isEmpty(tj01IdArr)) {
                doDistribute(req, tj01IdArr, nowDate, username);
            }
        }
        // 分配多参数监测仪
        if(StringUtils.isNotBlank(tj02Id)){
            String[] tj02IdArr = tj02Id.split(",");
            if (!ArrayUtils.isEmpty(tj02IdArr)) {
                doDistribute(req, tj02IdArr, nowDate, username);
            }
        }
        // 分配心电血压监测仪
        if(StringUtils.isNotBlank(tj03Id)){
            String[] tj03IdArr = tj03Id.split(",");
            if (!ArrayUtils.isEmpty(tj03IdArr)) {
                doDistribute(req, tj03IdArr, nowDate, username);
            }
        }
    }

    private void doDistribute(EquipmentDistributionReq req, String[] equipmentIdArr, Date nowDate, String operateUser) {
        for (String id : equipmentIdArr) {
            TEquipmentInfo baseInfo = tEquipmentInfoMapper.selectTEquipmentInfoById(id);
            if(baseInfo == null) {
                continue;
            }
            if(EquipmentConstant.DISTRIBUTE_FLAG_YES.equals(baseInfo.getDistributeFlag())) {
                continue;
            }

            THospitalEquipment hospitalEquipment = new THospitalEquipment();
            hospitalEquipment.setHospitalId(req.getHospitalId());
            hospitalEquipment.setEquipmentId(id);
            hospitalEquipment.setDistributeStatus(EquipmentConstant.DISTRIBUTE_FLAG_YES);
            hospitalEquipment.setDistributeTime(nowDate);

            if(StringUtils.isNotBlank(req.getDeptId())) {
                hospitalEquipment.setDeptId(req.getDeptId());
                hospitalEquipment.setAllocationFlag(EquipmentConstant.DISTRIBUTE_FLAG_YES);
            }

            if(EquipmentConstant.EQUIPMENT_TYPE_TJ01.equals(baseInfo.getEquipmentType())) {
                hospitalEquipment.setUsageFrequency(req.getUsageFrequency());
                hospitalEquipment.setReminderThreshold(req.getReminderThreshold());
            }
            if(EquipmentConstant.EQUIPMENT_TYPE_TJ02.equals(baseInfo.getEquipmentType())) {
                hospitalEquipment.setTestFlag(req.getTestFlag());
            }

            hospitalEquipment.setCreateBy(operateUser);
            hospitalEquipment.setCreateTime(nowDate);
            hospitalEquipment.setUpdateBy(operateUser);
            hospitalEquipment.setUpdateTime(nowDate);
            tHospitalEquipmentMapper.insertTHospitalEquipment(hospitalEquipment);

            TEquipmentInfo tEquipmentInfo = new TEquipmentInfo();
            tEquipmentInfo.setId(id);
            tEquipmentInfo.setDistributeFlag(EquipmentConstant.DISTRIBUTE_FLAG_YES);
            tEquipmentInfo.setHospitalId(req.getHospitalId());
            tEquipmentInfoMapper.updateTEquipmentInfo(tEquipmentInfo);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult doRecovery(String[] ids) {

        StringBuilder sb = new StringBuilder();
        int success = 0;
        for (String id : ids) {
            // 查询设备信息
            TEquipmentInfo baseInfo = tEquipmentInfoMapper.selectTEquipmentInfoById(id);
            if(baseInfo == null) {
                sb.append("数据ID：").append(id).append("不存在、");
                continue;
            }
            if(EquipmentConstant.DISTRIBUTE_FLAG_NO.equals(baseInfo.getDistributeFlag())) {
                // 未分配
                sb.append(baseInfo.getEquipmentNo()).append("未分配、");
                continue;
            }
            // 查询分配信息
            THospitalEquipment hospitalEquipment = tHospitalEquipmentMapper.selectByEquipmentId(id);
            if(hospitalEquipment == null) {
                sb.append("医院设备：").append(baseInfo.getEquipmentNo()).append("不存在、");
                continue;
            }
            if(EquipmentConstant.DISTRIBUTE_FLAG_NO.equals(hospitalEquipment.getDistributeStatus())) {
                // 已收回
                sb.append(baseInfo.getEquipmentNo()).append("已收回、");
                continue;
            }
            if(EquipmentConstant.USE_FLAG_YES.equals(hospitalEquipment.getUseFlag())) {
                // 设备使用中
                sb.append(baseInfo.getEquipmentNo()).append("正在使用中、");
                continue;
            }

            hospitalEquipment.setDistributeStatus(EquipmentConstant.DISTRIBUTE_FLAG_NO);
            hospitalEquipment.setRecoveryTime(DateUtils.getNowDate());
            tHospitalEquipmentMapper.updateTHospitalEquipment(hospitalEquipment);

            baseInfo.setDistributeFlag(EquipmentConstant.DISTRIBUTE_FLAG_NO);
            baseInfo.setHospitalId("");
            tEquipmentInfoMapper.updateTEquipmentInfo(baseInfo);

            success += 1;
        }

        if(success == ids.length) {
            return AjaxResult.success();
        } else {
            if (sb.length() > 0) {
                // 删除最后一个字符
                sb.deleteCharAt(sb.length() - 1);
            }
            return AjaxResult.success(sb.toString());
        }
    }

    @Override
    public int changeTestStatus(THospitalEquipment hosEq) {
        return tHospitalEquipmentMapper.updateTHospitalEquipment(hosEq);
    }
}
